<?php

/*
 * Google API
 * and open the template in the editor.
 */

/**
 * Description of GooglePlace
 *
 * @author wzhzhang
 */
class GoogleApi
{
    
    const DEFAULT_PLACE = '火星';

    protected $_appkey;
    
    /**
     * @var array 
     */
    
    private $_types = array
    (
        'street' => array( 'street_address' ) ,
        'district' => array( 'sublocality' , 'political' ) ,
        'city' => array( 'locality' , 'political' )
    );

    /**
     * 单例对象
     */
    public static $singletonObject = null;
    
    private $_apiAddr = array
    (
        'maps/geocode' => 'http://maps.google.cn/maps/api/geocode/json' ,
    );

    /**
     * 获取单例
     * @param $uId 用户ID
     * @return GoogleApi
     */
    public static function getInstance() {
        if (self::$singletonObject == null) {
            self::$singletonObject = new self();
        }

        return self::$singletonObject;
    }

    protected function __construct() {
        //$apnsConfig = & Common::getConfig('ApnsConfig');
        //$this->_currentMode = $apnsConfig['mode'];
        //$this->_cert = $apnsConfig['cert'];
        $this->_appkey = 'AIzaSyA5AU13UhnW-i1CE5yWO0KaDyMo0bJj5A4';
    }

    /**
     * 根据经纬度获取地点名
     * 
     * @param float $lat
     * @param float $lng
     * @param string $type
     * @return string 
     */
    public function getPlace( $lat , $lng , $type = 'city' )
    {
        try 
        {
            $result = Helper_Curl::curl($this->_apiAddr['maps/geocode'], array('latlng' => "{$lat},{$lng}" , 'sensor' => "false" ) );
            $result = json_decode($result, true);
        } catch (Exception $e) {
            unset($e);
            return self::DEFAULT_PLACE;
        }
        
        
        foreach( $result['results'] as $item )
        {
            if( $item['types'] == $this->_types[$type] )
            {
                return $item['formatted_address'];
            }
        }
        
        return self::DEFAULT_PLACE;
        
    }

}